package com.yupi.yuoj.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.constant.CommonConstant;
import com.yupi.yuoj.exception.BusinessException;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.judge.codesandbox.model.JudgeInfo;
import com.yupi.yuoj.model.dto.question.QuestionEsDTO;
import com.yupi.yuoj.model.dto.question.QuestionQueryRequest;
import com.yupi.yuoj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yupi.yuoj.model.entity.Question;
import com.yupi.yuoj.model.entity.QuestionSubmit;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.QuestionSubmitVO;
import com.yupi.yuoj.model.vo.QuestionVO;
import com.yupi.yuoj.model.vo.UserVO;
import com.yupi.yuoj.repository.QuestionEsRepository;
import com.yupi.yuoj.service.QuestionService;
import com.yupi.yuoj.mapper.QuestionMapper;
import com.yupi.yuoj.service.UserService;
import com.yupi.yuoj.utils.SqlUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import jakarta.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 李胜
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2025-08-27 16:19:26
*/
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService{

    @Resource
    private UserService userService;

    @Resource
    private QuestionEsRepository questionRepository; // ES仓库

    @Resource
    private ElasticsearchClient elasticsearchClient;

    @Override
    public org.springframework.data.domain.Page searchFromEs(String keyword, int pageNum, int pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        try {
            // 1. 构建搜索请求
            SearchResponse<QuestionEsDTO> searchResponse = elasticsearchClient.search(s -> s
                            .index("question")
                            .query(q -> q
                                    .multiMatch(m -> m
                                            .query(keyword)
                                            // 【重要修改】只在真正的文本字段中进行全文搜索
                                            .fields("title", "content", "tags")
                                    )
                            )
                            .from((int) pageRequest.getOffset()) // 使用 getOffset() 更安全
                            .size(pageRequest.getPageSize()),
                    QuestionEsDTO.class
            );            // 2. 解析响应
            long total = searchResponse.hits().total().value();
            List<QuestionEsDTO> list = searchResponse.hits().hits().stream()
                    .map(Hit::source)
                    .collect(Collectors.toList());

            return new PageImpl<>(list, pageRequest, total);

        } catch (IOException e) {
            // 处理异常，例如记录日志
            // log.error("Elasticsearch search failed", e);
            return org.springframework.data.domain.Page.empty(pageRequest);
        }
    }

    /**
     * 验证question是否合法
     * @param question
     * @param add
     */
    @Override
    public void validQuestion(Question question, boolean add) {
        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = question.getTitle();
        String content = question.getContent();
        String tags = question.getTags();
        String answer = question.getAnswer();
        String judgeCase = question.getJudgeCase();
        String judgeConfig = question.getJudgeConfig();
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签过长");
        }
        if (StringUtils.isNotBlank(content) && title.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案过长");
        }
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题用例过长");
        }
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "判题配置过长");
        }
    }

    /**
     * 关联创建用户
     * @param question
     * @param request
     * @return
     */
    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        Long userId = questionVO.getUserId();
        User createUser = userService.getById(userId);
        ThrowUtils.throwIf(createUser==null, ErrorCode.NOT_FOUND_ERROR);
        UserVO userVO = userService.getUserVO(createUser);
        questionVO.setUserVO(userVO);
        return questionVO;
    }

    /**
     * 根据查询条件获取QueryWrapper
     * @param questionQueryRequest
     * @return
     */
    @Override
    public Wrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> questionQueryWrapper = new QueryWrapper<>();

        Long id = questionQueryRequest.getId();
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        List<String> tags = questionQueryRequest.getTags();
        String answer = questionQueryRequest.getAnswer();
        Long userId = questionQueryRequest.getUserId();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();

        //拼接查询条件
        questionQueryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        questionQueryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        questionQueryWrapper.like(StringUtils.isNotBlank(answer), "answer", answer);
        if (CollectionUtils.isNotEmpty(tags)) {
            questionQueryWrapper.and(qw -> {
                tags.forEach(tag -> qw.or().like("tags", "\"" + tag + "\""));
            });
        }        questionQueryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        questionQueryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        questionQueryWrapper.eq("isDelete", false);
        questionQueryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        return questionQueryWrapper;
    }

    /**
     * 获取分页脱敏Question
     * @param pages
     * @param request
     * @return
     */
    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> pages, HttpServletRequest request) {
        List<Question> records = pages.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(pages.getCurrent(), pages.getSize(), pages.getTotal());
        if (CollectionUtils.isEmpty(records)) {
            return questionVOPage;
        }
        // 1.关联用户信息
        Set<Long> userIdSet = records.stream().map(Question::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        // 填充信息
        List<QuestionVO> questionVOList = records.stream().map(question -> {
            QuestionVO questionVO = QuestionVO.objToVo(question);
            Long userId = question.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionVO.setUserVO(userService.getUserVO(user));
            return questionVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }


    /**
     * 分页获取提交通过的题目
     * @param questionQueryRequest
     * @param loginUser
     * @return
     */
    @Override
    public Page<Question> listQuestionVOMyAcByPage(Page<Question> page, QuestionQueryRequest questionQueryRequest, User loginUser) {
        Page<Question> questionPage = this.baseMapper.selectMyAcQuestionPage(page, questionQueryRequest, loginUser.getId());
        return questionPage;
    }

    /**
     * 分页获取提交历史
     *
     * @param page
     * @param questionSubmitQueryRequest
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> listQuestionVOMyHistorySubmitByPage(Page<QuestionSubmit> page, QuestionSubmitQueryRequest questionSubmitQueryRequest, User loginUser) {
        Page<QuestionSubmit> questionSubmitPage = this.baseMapper.selectMyHistorySubmitQuestionPage(page, questionSubmitQueryRequest, loginUser.getId());
        List<QuestionSubmit> questionSubmits = questionSubmitPage.getRecords();
        Gson gson = new Gson();
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmits.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = new QuestionSubmitVO();
            BeanUtils.copyProperties(questionSubmit, questionSubmitVO);
            JudgeInfo judgeInfo = gson.fromJson(questionSubmit.getJudgeInfo(), JudgeInfo.class);
            QuestionVO questionVO = new QuestionVO();
            BeanUtils.copyProperties(this.baseMapper.selectById(questionSubmit.getQuestionId()), questionVO);
            questionSubmitVO.setQuestionVO(questionVO);
            questionSubmitVO.setJudgeInfo(judgeInfo);
            return questionSubmitVO;
        }).toList();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>();
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        questionSubmitVOPage.setTotal(questionSubmitPage.getTotal());
        questionSubmitVOPage.setCurrent(questionSubmitPage.getCurrent());
        return questionSubmitVOPage;
    }
}




